package com.hnx.admin.aurora.system.service.impl;

import com.hnx.admin.aurora.annotation.Pager;
import com.hnx.admin.aurora.annotation.RepeatValidator;
import com.hnx.admin.aurora.api.cache.CacheAPI;
import com.hnx.admin.aurora.api.sys.IPAddrValidator;
import com.hnx.admin.aurora.captcha.api.CaptchaAPI;
import com.hnx.admin.aurora.enums.BusinessType;
import com.hnx.admin.aurora.redis.RedisCache;
import com.hnx.admin.aurora.system.domain.dto.sysConfig.entity.SysConfigDTO;
import com.hnx.admin.aurora.system.domain.param.sysConfig.form.SysConfigForm;
import com.hnx.admin.aurora.system.domain.param.sysConfig.query.SysConfigQuery;
import com.hnx.admin.aurora.system.mapper.sysConfig.SysConfigMapper;
import com.hnx.admin.aurora.system.service.SysConfigService;
import com.hnx.admin.aurora.utils.IPUtil;
import com.hnx.admin.aurora.web.json.ResultJson;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/*
创建人： 倔强的头发
创建时间：2025/6/17
功能描述:

*/
@Service
@RequiredArgsConstructor
public class SysConfigServiceImpl implements SysConfigService, CacheAPI, CaptchaAPI , IPAddrValidator {
    private final RedisCache redisCache;
    private final SysConfigMapper configMapper;
//    @Override
//    public void match(Object key, HttpServletRequest request) {
//        boolean captchaEnabled = selectCaptchaEnabled();
//        if (captchaEnabled) {
//            if (key instanceof LoginQuery) {
//                LoginQuery userQuery = (LoginQuery) key;
//                String verifyKey = captchaKey(userQuery.getUuid());
//                String captcha = redisCache.getCacheObject(verifyKey, String.class);
//                if (StringUtils.isBlank(userQuery.getCode())) {
//                    throw new CaptchaEmptyException();
//                }
//                if (StringUtils.isBlank(captcha)) {
//                    throw new CaptchaExpireException();
//                }
//                if (!captcha.equalsIgnoreCase(userQuery.getCode())) {
//                    redisCache.deleteObject(verifyKey);
//                    throw new CaptchaException();
//                }
//            }
//        }
//    }

    @Override
    public boolean selectCaptchaEnabled() {
        String captchaEnabled = selectConfigByKey("sys.account.captchaEnabled");
        if (StringUtils.isBlank(captchaEnabled)) {
            return true;
        }
        return Boolean.parseBoolean(captchaEnabled);
    }

    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = redisCache.getCacheObject(configKey(configKey), String.class);
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        SysConfigQuery config = new SysConfigQuery();
        config.setConfigKey(configKey);
        SysConfigDTO retConfig = configMapper.selectConfig(config);
        if (Objects.nonNull(retConfig)) {
            redisCache.setCacheObject(configKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    @Override
    public ResultJson selectConfigById(String configId) {
        SysConfigQuery config = new SysConfigQuery();
        config.setConfigId(configId);
        SysConfigDTO dto = configMapper.selectConfig(config);
        return ResultJson.data(dto);
    }

    @Override
    @Pager
    public ResultJson selectConfigList(SysConfigQuery config) {
        List<SysConfigDTO> list = configMapper.selectConfigList(config);
        return ResultJson.success().add("rows", list);
    }

    @Override
    @RepeatValidator
    public ResultJson insertConfig(SysConfigForm config) {
        int row = configMapper.insertConfig(config);
        return ResultJson.condition(row);
    }

    @Override
    public ResultJson deleteConfigByIds(String[] configIds) {
        for (String configId : configIds) {
            SysConfigDTO config = (SysConfigDTO) selectConfigById(configId).get("data");
            if (StringUtils.equals("Y", config.getConfigType())) {
                throw new RuntimeException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
            configMapper.deleteConfigById(configId);
            redisCache.delete(SYS_CONFIG_KEY + config.getConfigKey());
        }
        return ResultJson.success();
    }

    @Override
    @RepeatValidator(type = BusinessType.UPDATE)
    public ResultJson updateConfig(SysConfigForm config) {
        int row = configMapper.updateConfig(config);
        redisCache.delete(SYS_CONFIG_KEY + config.getConfigKey());
        return ResultJson.condition(row);
    }

    @Override
    public ResultJson resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
        return ResultJson.success();
    }
    public void clearConfigCache() {
        Collection<String> keys = redisCache.keys(SYS_CONFIG_KEY + "*");
        redisCache.deleteObject(keys);
    }

    private void loadingConfigCache() {
        List<SysConfigDTO> configsList = configMapper.selectConfigList(new SysConfigQuery());
        for (SysConfigDTO config : configsList) {
            if (redisCache.hasKey(configKey(config.getConfigKey()))) {
                redisCache.deleteObject(configKey(config.getConfigKey()));
            }
            redisCache.setCacheObject(configKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    @Override
    public boolean isValid(HttpServletRequest request) {
        String blackIp = selectConfigByKey("sys.login.blackIPList");
        if (org.springframework.util.StringUtils.hasText(blackIp)) {
            List<String> list = Arrays.stream(blackIp.split(";")).collect(Collectors.toList());
            String clientIP = IPUtil.getClientIp(request);
            if (IPUtil.matchIP(clientIP, list)) {
                return false;
            }
        }
        return true;
    }
}
